package com.ultrasoft.farmasoft.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;




import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;




import com.ultrasoft.farmasoft.domain.Activesubstance;
import com.ultrasoft.farmasoft.domain.Attribute;
import com.ultrasoft.farmasoft.domain.Composition;
import com.ultrasoft.farmasoft.domain.Locality;
import com.ultrasoft.farmasoft.domain.Pharmacystock;
import com.ultrasoft.farmasoft.domain.Product;
import com.ultrasoft.farmasoft.domain.Productattribute;
import com.ultrasoft.farmasoft.domain.Productattributes;
import com.ultrasoft.farmasoft.domain.Provider;
import com.ultrasoft.farmasoft.domain.Providerpharmacy;
import com.ultrasoft.farmasoft.domain.Typecomposition;
import com.ultrasoft.farmasoft.domain.Userpharmacy;
import com.ultrasoft.farmasoft.service.ConfigServiceProducts;
import com.ultrasoft.farmasoft.service.GeneralAdministrationService;
import com.ultrasoft.farmasoft.service.HumanResourcesService;
import com.ultrasoft.farmasoft.util.UtilCommon;
import com.ultrasoft.farmasoft.util.UtilConverter;






@Controller
@SessionAttributes({"s_UserPharmacy"})
@RequestMapping(value="/ProductAndActiveSubstance")
public class ProductAndActiveSubstanceController {
	
	private HttpSession session;
	private Userpharmacy s_UserPharmacy;
	private int s_userId;
	private int s_pharmacyId;
	
	private String activeSubstanceId_	= "_activeSubstanceId";
	private String productId_			= "_productId";
	private String providerId_			= "_providerId";
	
	protected Logger logger;
	private final ConfigServiceProducts configServiceProducts;
	private final GeneralAdministrationService generalAdminService;
	private final HumanResourcesService humanResourcesService;

	
	@Autowired
    public ProductAndActiveSubstanceController(ConfigServiceProducts configServiceProducts, GeneralAdministrationService generalAdminService,HumanResourcesService humanResourcesService) {
        this.configServiceProducts 	= configServiceProducts;
        this.generalAdminService 	= generalAdminService;
        this.humanResourcesService 	= humanResourcesService;
        logger = LoggerFactory.getLogger(getClass());
    }
	
	private boolean sessionControl(HttpServletRequest request){
		  boolean res = false;
		  session = request.getSession(true);
		  if(session.getAttribute("s_UserPharmacy") != null){
			   s_UserPharmacy  = (Userpharmacy)session.getAttribute("s_UserPharmacy");
			   s_userId   = s_UserPharmacy.getUser().getUserId();
			   s_pharmacyId  = s_UserPharmacy.getPharmacy().getPharmacyId();
			   res = true;
		  }
		  return res;
	}	
	
    //start esencial
	private String redirectProductAndActiveSubstance(HttpServletRequest request){
		return "redirect:/configActivePrinciple?"+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_); 
	}
	private String handleRedirectProductAndActiveSubstance(HttpServletRequest request,String headMain) {
    	try {
    		return "redirect:/"+headMain+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+
    				"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_)+
    				"&"+UtilCommon.optionId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.optionId_); 
		}catch (Exception e) {
			return redirectProductAndActiveSubstance(request);
		}
    }		

	//Control main page ProductAndActiveSubstance
	@RequestMapping(value="/configActivePrinciple", method = RequestMethod.GET)	
	public String handleFront(HttpServletRequest request) throws ServletException {
		if(this.sessionControl(request)){
			return UtilCommon.fProductAndActiveSubstance+"productActiveSubstance";				
		}else{
			return "redirect:/closeSesion";
		}		     	 		

	}	
		
	
	// Add submenu the ProductAndActiveSubstance TypeOfComposition*/
	@RequestMapping(value="/compositionType", method=RequestMethod.GET)
	public String handleRequestCompositionType(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){
			List<Typecomposition> typeComposition = configServiceProducts.getTypecompositionList();
			model.addAttribute("typeComposition",typeComposition);
			return UtilCommon.fTypeOfComposition+"adminTypeOfComposition";
		}else
			return redirectProductAndActiveSubstance(request);
	}			
	// Method add and edit TypeOfComposition*/
	@RequestMapping(value = "/addEditTypeOfComposition", method = RequestMethod.POST)
	public @ResponseBody String handleRequestAddEditTypeOfComposition( @RequestParam Integer typeCompositionId, @RequestParam Integer accion, @RequestParam String name){
		String msg="";
		if(accion == 0){
			msg="Se agrego ";
			configServiceProducts.addTypeComposition(new Typecomposition(typeCompositionId, name));
		}
		if(accion == 1){
			msg="Se Edito ";
			Typecomposition tc = configServiceProducts.searchTypecompositionByID(typeCompositionId);
			tc.setName(name);
			configServiceProducts.updateTypeComposition(tc);
		}
		return msg+"correctamente!!!";
	}
	// Method remove TypeOfComposition*/
	@RequestMapping(value = "/removeTypeOfComposition", method = RequestMethod.GET)
	public @ResponseBody String handleRequestRemoveTypeOfComposition(@RequestParam Integer typeCompositionId,@RequestParam String name){
		configServiceProducts.removeTypeComposition(configServiceProducts.searchTypecompositionByID(typeCompositionId));	
		return "El Pais "+name+" se Elimino correctamente!!!";
	}		
		
	
	// Add submenu the ActiveSubstance
	@RequestMapping(value="/configActiveSubstance", method=RequestMethod.GET)
	public String handleRequestConfigActivePrinciple(HttpServletRequest request, Model model,  @Valid Activesubstance actSubstance) throws ServletException {
		if(this.sessionControl(request)){
			List<Activesubstance> activeSubstance = configServiceProducts.getActivesubstanceList();
			model.addAttribute("substance", activeSubstance);
			return UtilCommon.fActiveSubstance+"adminActiveSubstance";
		}else
			return redirectProductAndActiveSubstance(request);
	}	
	
	
	@RequestMapping(value="/newActiveSubstance", method=RequestMethod.GET)
	public String handleRequestNewActiveSubstance(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){					
			return UtilCommon.fActiveSubstance+"formActiveSubstance";
		}else
			return redirectProductAndActiveSubstance(request);
	}			 
	@RequestMapping(value="/newActiveSubstance" , method = RequestMethod.POST)
	public String onSubmitRequestNewActiveSubstance(HttpServletRequest request){
		if(this.sessionControl(request)){		
			String name = request.getParameter("name");
			String synonyms = request.getParameter("synonyms");
			String therapeuticAction = request.getParameter("therapeuticAction");
			String properties = request.getParameter("properties");					
			String[] productAttributeValues = request.getParameterValues("productAttributeValues");
			
			try{
				Integer substanceActiveId = configServiceProducts.getSubstanceActiveId();
				Activesubstance activeSustance = new Activesubstance();
				activeSustance.setActiveSubstanceId(substanceActiveId);
				activeSustance.setName(name);
				activeSustance.setSynonyms(synonyms); 
				activeSustance.setTherapeuticAction(therapeuticAction);
				activeSustance.setProperties(properties);
				
				List<Attribute> attributes = new ArrayList<Attribute>();
				Integer attributeId = configServiceProducts.getAttributeId();
				for(String val:productAttributeValues){
					String[] values = val.split("\\|\\|");
					Attribute att = new Attribute(attributeId, substanceActiveId, values[0], values[1], Short.parseShort(values[2]));								
					attributes.add(att);
					attributeId++;
				}
				activeSustance.setAttributeCollection(attributes);
				configServiceProducts.saveSubstanceActive(activeSustance);
			}catch(Exception e){
				//System.out.println("Errorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr = "+e.getMessage());
			}
			return handleRedirectProductAndActiveSubstance(request,"ProductAndActiveSubstance/configActiveSubstance?");	
		}else
			return redirectProductAndActiveSubstance(request);
	}			
	@RequestMapping(value="/activeSubstanceEdit", method=RequestMethod.GET)
	public String handleRequestActiveSubstanceEdit(HttpServletRequest request, Model model) throws ServletException {		    	
		if(this.sessionControl(request)){			
			model.addAttribute("listAttribute", configServiceProducts.getAttributeListByActiveSubstanceId(UtilConverter.converterStringToInteger(request,activeSubstanceId_)));
			model.addAttribute("activeSubstance", configServiceProducts.searchActivesubstanceByID(UtilConverter.converterStringToInteger(request, activeSubstanceId_)));
			return UtilCommon.fActiveSubstance+"formActiveSubstance";
		}else
			return redirectProductAndActiveSubstance(request);
	}
	@RequestMapping(value="/activeSubstanceEdit" , method = RequestMethod.POST)
	public String onSubmitRequestHumanResourcesRegisterAdministrativeEditClassRoom(HttpServletRequest request){
		if(this.sessionControl(request)){		
			Activesubstance activeSustance= configServiceProducts.searchActivesubstanceByID(UtilConverter.converterStringToInteger(request,"activeSubstanceId"));
			activeSustance.setName(UtilConverter.converterStringToString(request, "name"));
			activeSustance.setSynonyms(UtilConverter.converterStringToString(request, "synonyms")); 
			activeSustance.setTherapeuticAction(UtilConverter.converterStringToString(request, "therapeuticAction"));
			activeSustance.setProperties(UtilConverter.converterStringToString(request, "properties"));					
			try {
				List<Attribute> listAttribute = configServiceProducts.getAttributeListByActiveSubstanceId(activeSustance.getActiveSubstanceId());
				for (Attribute attribute2 : listAttribute) {
					configServiceProducts.removeAttribute(attribute2);
				}
				String[] productAttributeValues = request.getParameterValues("productAttributeValues");
				List<Attribute> attributes = new ArrayList<Attribute>();
				Integer attributeId = configServiceProducts.getAttributeId();
				for(String val:productAttributeValues){
					String[] values = val.split("\\|\\|");
					Attribute att = new Attribute(attributeId, activeSustance.getActiveSubstanceId(), values[0], values[1], Short.parseShort(values[2]));
					attributes.add(att);
					attributeId++;
				}
				activeSustance.setAttributeCollection(attributes);
			} catch (Exception e) {
				// TODO: handle exception
			}
			configServiceProducts.updateActiveSubstance(activeSustance);
			return handleRedirectProductAndActiveSubstance(request,"ProductAndActiveSubstance/configActiveSubstance?");	
		}else
			return redirectProductAndActiveSubstance(request);
	}  		    
	@RequestMapping(value = "/removeActiveSubstance", method = RequestMethod.GET)
	public @ResponseBody String handleRequestRemoveActiveSubstance(@RequestParam Integer activeSubstanceId,@RequestParam String name, HttpServletRequest request){
		Activesubstance as = configServiceProducts.searchActivesubstanceByID(activeSubstanceId);
		as.setAttributeCollection(configServiceProducts.getAttributeListByActiveSubstanceId(activeSubstanceId));
		List<Product> listProduct = configServiceProducts.getListProductByActiveSubstanceId(activeSubstanceId);
		String showed = "El Principio Activo: "+name+" se Elimino correctamente!!!";
		if(listProduct.isEmpty())
			configServiceProducts.removeActiveSubstance(as);
		else
			showed = "El Principio Activo: "+name+" no se Eliminara debido a que ya esta utilizado por el producto!!!";
		return showed;
	} 	
	@RequestMapping(value="/activeSubstanceShowDetail", method=RequestMethod.GET)
	public String handleRequestActiveSubstanceShowDetail(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){
			Integer activeSubstanceId = UtilConverter.converterStringToInteger(request,activeSubstanceId_);
			Activesubstance activeSubstance = configServiceProducts.searchActivesubstanceByID(activeSubstanceId);
			activeSubstance.setAttributeCollection(configServiceProducts.getAttributeListByActiveSubstanceId(activeSubstanceId));
			model.addAttribute("activeSubstance", activeSubstance);
			return UtilCommon.fReferenceAdd+"showDetailActiveSubstance";
		}else
			return redirectProductAndActiveSubstance(request);
	}	
	private Activesubstance getActiveSubstanceTemp(Activesubstance activeSubstance){
		Activesubstance temp = new Activesubstance(activeSubstance.getActiveSubstanceId(),activeSubstance.getSynonyms(),activeSubstance.getName(),activeSubstance.getTherapeuticAction(),activeSubstance.getProperties());
		List<Attribute> attributeList = (List)activeSubstance.getAttributeCollection();  
		List<Attribute> attributeListTemp = new ArrayList<Attribute>();  
		for (Attribute attribute : attributeList) {
			Attribute attributeTemp = new Attribute(attribute.getAttributePK().getAttributeId(),attribute.getAttributePK().getActiveSubstanceId(),attribute.getName(),attribute.getDetail(),attribute.getOrder());
			attributeListTemp.add(attributeTemp);
		}
		temp.setAttributeCollection(attributeListTemp);		
		return temp;
	}
			 
			 
			 
	private String[][] changeRowsToColumns(String[] list){		
		String[] arrayString0 = list[0].split("\\|\\|");					
		String[] arrayString = arrayString0[1].split("\\|\\*\\*\\|");			
		String[][]  matrix = new String[list.length][arrayString.length];			// list.length: filas			
		for(int x=0; x < matrix.length; x++){ 
			String[] stringArray = list[x].split("\\|\\|");					
			String name = stringArray[0];
			String[] stringArrayContain = stringArray[1].split("\\|\\*\\*\\|");	
			for(int y=0; y < matrix[x].length; y++) {
				matrix[x][y]=name+"||"+stringArrayContain[y];
			}					
		}		
		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix[i].length; j++) {
				System.out.print(matrix[i][j]+" ");
			}
			System.out.println();
		}		
		String[][]  res= new String[arrayString.length][list.length];
		for(int x=0; x < matrix[0].length; x++){ 
			for(int y=0; y < matrix.length; y++) 
				res[x][y] = matrix[y][x];
		}		
		return res;
	}	 
		    
	@RequestMapping(value="/products", method=RequestMethod.GET)
	public String handleRequestProducts(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){
			model.addAttribute("listProduct",configServiceProducts.getListProduct(true));
			model.addAttribute("listProductInActive",configServiceProducts.getListProduct(false));
			return UtilCommon.fProducts+"adminProducts";
		}else
			return redirectProductAndActiveSubstance(request);
	}
	
	@RequestMapping(value="/productsNew", method=RequestMethod.GET)
	public String handleRequestProductsNew(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){			
			model.addAttribute("listGenericValue",configServiceProducts.getListGenericValueByPharmacyIdByGroup(0,(short)1));	//
			model.addAttribute("listTypeComposition",configServiceProducts.getTypecompositionList());
			model.addAttribute("listActiveSubstance",configServiceProducts.getActivesubstanceList());
			model.addAttribute("listProductAttribute",configServiceProducts.getListProductAttribute());
			model.addAttribute("listProvider",configServiceProducts.getListProvider(s_pharmacyId,true));
			model.addAttribute("product",new Product());		
			return UtilCommon.fProducts+"formProducts";
		}else
			return redirectProductAndActiveSubstance(request);
	}		
	@RequestMapping(value="/productsNew" , method = RequestMethod.POST)
    public String onSubmitRequestProductsNew(@Valid Product product, BindingResult result,Model model,HttpServletRequest request){		
		if(result.hasErrors()){
			System.out.println("errorrrrrrrrrrrrrrrrrrr");
			model.addAttribute("listGenericValue",configServiceProducts.getListGenericValueByPharmacyIdByGroup(0,(short)1));	
			model.addAttribute("listTypeComposition",configServiceProducts.getTypecompositionList());
			model.addAttribute("listActiveSubstance",configServiceProducts.getActivesubstanceList());
			model.addAttribute("listProductAttribute",configServiceProducts.getListProductAttribute());
			model.addAttribute("listProvider",configServiceProducts.getListProvider(s_pharmacyId,true));
			return UtilCommon.fProducts+"formProducts";
		}
		try {
			String[] list=request.getParameterValues("compositionsValues");			
			String[][]  matrizCadenaFinal = changeRowsToColumns(list);
			for(int x=0; x < matrizCadenaFinal.length; x++){ 
				int tempProductId 	= configServiceProducts.searchProductByProductIdMax();
				Product p = new Product(product.getProductPK().getProviderId(),(tempProductId+1));
				p.setActive(true);
				p.setName(product.getName());
				p.setPresentation(product.getPresentation());
				
				Activesubstance activeSubstance = configServiceProducts.searchActivesubstanceByID(Integer.parseInt(product.getGenericName()));
				p.setActiveSubstanceId(activeSubstance);
				p.setGenericName(activeSubstance.getName());
				p.setGeneralIndication(product.getGeneralIndication());
				p.setRemarkComposition(product.getRemarkComposition());
				p.setCodeBar(product.getCodeBar());
				Userpharmacy up = humanResourcesService.searchUserPharmacyByPharmacyIdByUserId(s_pharmacyId,s_userId);
				p.setUserpharmacy(up);
				configServiceProducts.addProduct(p);
				
				for(int y=0; y < matrizCadenaFinal[x].length; y++) {
					System.out.print(matrizCadenaFinal[x][y]+" "); 
					String[] array = matrizCadenaFinal[x][y].split("\\|\\|");	
					String name=array[0];
					String[] compTypeArrayInto = array[1].split("&&");
										
					Composition composition = new Composition(null, name,compTypeArrayInto[1],true);
					Typecomposition typeCompodition = configServiceProducts.searchTypecompositionByID(Integer.parseInt(compTypeArrayInto[0]));
					composition.setTypeCompositionId(typeCompodition);
					composition.setProduct(p);
					composition.setValueRadio(1);
					if(compTypeArrayInto.length == 3)
						composition.setCheckHealth(compTypeArrayInto[2]);
					configServiceProducts.addComposition(composition);
				}	
				String[] listProductAttribute=request.getParameterValues("productAttributeValues");
				for (int i = 0; i < listProductAttribute.length; i++) {
					String[] stringArrayContain = listProductAttribute[i].split("&&");	
					
					Productattribute productAttribute = new Productattribute(null,stringArrayContain[0],stringArrayContain[1],Short.parseShort(stringArrayContain[2]));
					configServiceProducts.addProductAttribute(productAttribute);
					configServiceProducts.addProductAttributes(new Productattributes(productAttribute, p));
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}				
		System.out.println(request.getParameterMap());
		return handleRedirectProductAndActiveSubstance(request,"ProductAndActiveSubstance/products?");	
    }	
	
	@RequestMapping(value="/productsEdit", method=RequestMethod.GET)
	public String handleRequestProductsEdit(HttpServletRequest request, Model model) throws ServletException {			
		if(this.sessionControl(request)){
			int tempProviderId = UtilConverter.converterStringToInteger(request,providerId_);
			int tempProductId = UtilConverter.converterStringToInteger(request,productId_);
			Product product = configServiceProducts.searchProductByProviderIdByProductId(tempProviderId,tempProductId);
			List<Composition> listComposition = configServiceProducts.getListCompositionByProviderIdByProductIdByActive(tempProviderId,tempProductId,true);
			List<Productattributes>  listProductAttributes = configServiceProducts.getListProductAttributesByProviderIdByProductId(tempProviderId,tempProductId);
			if(product == null || listComposition.isEmpty() || listProductAttributes.isEmpty()){
				if(listComposition.isEmpty())
					System.out.println(" listComposition is empty "+listComposition.isEmpty());
				if(listProductAttributes.isEmpty())
					System.out.println(" listProductAttributes is empty "+listProductAttributes.isEmpty());
				return handleRedirectProductAndActiveSubstance(request,"ProductAndActiveSubstance/products?");	
			}
			model.addAttribute("tempValueQuantityRadio",listComposition.get(0).getValueRadio());
			model.addAttribute("listComposition",listComposition);
			model.addAttribute("listProductAttributes",listProductAttributes);
			model.addAttribute("listGenericValue",configServiceProducts.getListGenericValueByPharmacyIdByGroup(0,(short)1));	
			model.addAttribute("listTypeComposition",configServiceProducts.getTypecompositionList());
			model.addAttribute("listActiveSubstance",configServiceProducts.getActivesubstanceList());
			model.addAttribute("listProductAttribute",configServiceProducts.getListProductAttribute());
			model.addAttribute("listProvider",configServiceProducts.getListProvider(s_pharmacyId,true));
			model.addAttribute("product",product);
			return UtilCommon.fProducts+"formProducts";
		}else
			return redirectProductAndActiveSubstance(request);
	}	
	@RequestMapping(value="/productsEdit" , method = RequestMethod.POST)
    public String onSubmitRequestProductsEdit(@Valid Product product, BindingResult result,Model model,HttpServletRequest request){		
		if(result.hasErrors()){
			System.out.println("errorrrrrrrrrrrrrrrrrrr");
			model.addAttribute("listGenericValue",configServiceProducts.getListGenericValueByPharmacyIdByGroup(0,(short)1));	
			model.addAttribute("listTypeComposition",configServiceProducts.getTypecompositionList());
			model.addAttribute("listActiveSubstance",configServiceProducts.getActivesubstanceList());
			model.addAttribute("listProductAttribute",configServiceProducts.getListProductAttribute());
			model.addAttribute("listProvider",configServiceProducts.getListProvider(s_pharmacyId,true));
			return UtilCommon.fProducts+"formProducts";
		}				
		Product p = configServiceProducts.searchProductByProviderIdByProductId(UtilConverter.converterStringToInteger(request,providerId_),UtilConverter.converterStringToInteger(request,productId_));
		p.setActive(true);
		p.setName(product.getName());
		p.setPresentation(product.getPresentation());
		
		Activesubstance activeSubstance = configServiceProducts.searchActivesubstanceByID(Integer.parseInt(product.getGenericName()));
		p.setActiveSubstanceId(activeSubstance);
		p.setGenericName(activeSubstance.getName());
		p.setGeneralIndication(product.getGeneralIndication());
		p.setRemarkComposition(product.getRemarkComposition());
		p.setCodeBar(product.getCodeBar());
		configServiceProducts.updateProduct(p);		
		configServiceProducts.removeComposition(UtilConverter.converterStringToInteger(request,providerId_),UtilConverter.converterStringToInteger(request,productId_));
		
		try {
			String[] list=request.getParameterValues("compositionsValues");
			for (int i = 0; i < list.length; i++) {
				String[] stringArray = list[i].split("\\|\\|");					//	 working this way the ||
				String name = stringArray[0];
				String[] stringArrayContain = stringArray[1].split("\\|\\*\\*\\|");	
				for (int j = 0; j < stringArrayContain.length; j++) {
					String[] compTypeArrayInto = stringArrayContain[j].split("&&");
					
					Composition composition = new Composition(null, name,compTypeArrayInto[1],true);
					Typecomposition typeCompodition = configServiceProducts.searchTypecompositionByID(Integer.parseInt(compTypeArrayInto[0]));
					composition.setTypeCompositionId(typeCompodition);
					composition.setProduct(p);
					composition.setValueRadio(UtilConverter.converterStringToInteger(request,"valueRadio"));
					if(compTypeArrayInto.length == 3)
						composition.setCheckHealth(compTypeArrayInto[2]);
					
					configServiceProducts.addComposition(composition);
					System.out.println("agregando...");
				}
				
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		List<Productattributes> listProductAttributes =configServiceProducts.getListProductAttributesByProviderIdByProductId(UtilConverter.converterStringToInteger(request,providerId_),UtilConverter.converterStringToInteger(request,productId_));
		configServiceProducts.removeProductAttributes(UtilConverter.converterStringToInteger(request,providerId_),UtilConverter.converterStringToInteger(request,productId_));	
		for (Productattributes productattributes : listProductAttributes) {
			configServiceProducts.removeProductAttribute(productattributes.getProductattribute());
		}
		
		try {
			String[] listProductAttribute=request.getParameterValues("productAttributeValues");
			for (int i = 0; i < listProductAttribute.length; i++) {
				String[] stringArrayContain = listProductAttribute[i].split("&&");	
				Productattribute productAttribute = new Productattribute(null,stringArrayContain[0],stringArrayContain[1],Short.parseShort(stringArrayContain[2]));
				configServiceProducts.addProductAttribute(productAttribute);
				configServiceProducts.addProductAttributes(new Productattributes(productAttribute, p));
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		System.out.println(request.getParameterMap());
		return handleRedirectProductAndActiveSubstance(request,"ProductAndActiveSubstance/products?");	
    }
	@RequestMapping(value = "/ajaxGiveLowOrHighToProduct", method = RequestMethod.GET)
	public @ResponseBody String handleRequestAjaxGiveLowOrHighToProduct(@RequestParam Integer providerId,@RequestParam Integer productId,@RequestParam boolean active){
		Product p = configServiceProducts.searchProductByProviderIdByProductId(providerId, productId);
		p.setActive(active);
		configServiceProducts.updateProduct(p);
        String lowHigh = "";
        if(active)
        	lowHigh = " Se dio de Alta a ";
        else
        	lowHigh = " Se dio de Baja a ";
        return lowHigh;
    }
	
	@RequestMapping(value="/formNewProvider", method=RequestMethod.GET)
	public String handleRequestProviderR(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){
			model.addAttribute("countries", generalAdminService.getCountryList());
    		model.addAttribute("parts", generalAdminService.getRegionList());
    		model.addAttribute("towns", generalAdminService.getLocality());
			model.addAttribute("providerPharmacy",new Providerpharmacy());
			return UtilCommon.fReferenceAdd+"formProvider";
		}else
			return redirectProductAndActiveSubstance(request);
	}	
	@RequestMapping(value = "/formNewProvider", method = RequestMethod.POST)
   	public @ResponseBody Map<String, Object> handleRequestAddNewProvider(Providerpharmacy providerPharmacy, HttpServletRequest request){
		Locality tempLocality = generalAdminService.searchLocalityByRegionIdByLocalityId(providerPharmacy.getProvider().getLocality().getRegion().getRegionId(),UtilConverter.converterStringToShort(request,"tempLocalityId"));
		providerPharmacy.getProvider().setLocality(tempLocality);
		configServiceProducts.addProvider(providerPharmacy.getProvider());
		configServiceProducts.addProviderPharmacy(new Providerpharmacy(providerPharmacy.getProvider(),providerPharmacy.getPharmacy()));
				
		Integer id = configServiceProducts.searchProviderIdByProviderIdMax();
		List<Provider> listProvider = configServiceProducts.getListProvider(s_pharmacyId,true);
		List<Provider> providers = new ArrayList<Provider>();
		for (Provider provider : listProvider) {
			Provider p = new Provider(provider.getProviderId(),provider.getName(),provider.getClient());
			providers.add(p);
		}
		id = configServiceProducts.searchProviderIdByProviderIdMax();
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("id", id);
		map.put("providers",providers);
		return map;
    }
	
	@RequestMapping(value="/formEditProvider", method=RequestMethod.GET)
	public String handleRequestProviderE(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){
			Providerpharmacy pp = configServiceProducts.searchProviderPharmacy(s_pharmacyId,UtilConverter.converterStringToInteger(request,providerId_));
			model.addAttribute("countries", generalAdminService.getCountryList());
    		model.addAttribute("parts", generalAdminService.getRegionList());
    		model.addAttribute("towns", generalAdminService.getLocality());
    		model.addAttribute("regions",generalAdminService.getRegionList(pp.getProvider().getLocality().getRegion().getCountryId().getCountryId()));    		
    		model.addAttribute("localities",generalAdminService.getLocalityListByRegionIdByActive(pp.getProvider().getLocality().getLocalityPK().getRegionId(), true));
    		model.addAttribute("providerPharmacy",pp);
			return UtilCommon.fReferenceAdd+"formProvider";
		}else
			return redirectProductAndActiveSubstance(request);
	}
	@RequestMapping(value = "/formEditProvider", method = RequestMethod.POST)
   	public @ResponseBody Provider handleRequestEditProvider(Providerpharmacy providerPharmacy, HttpServletRequest request){
		Locality tempLocality = generalAdminService.searchLocalityByRegionIdByLocalityId(providerPharmacy.getProvider().getLocality().getRegion().getRegionId(),UtilConverter.converterStringToShort(request,"tempLocalityId"));
		Provider provider = new Provider(providerPharmacy.getProvider().getProviderId(),providerPharmacy.getProvider().getName(),providerPharmacy.getProvider().getClient());
		provider.setActive(providerPharmacy.getProvider().getActive());
		provider.setInitials(providerPharmacy.getProvider().getInitials());
		provider.setNit(providerPharmacy.getProvider().getNit());
		provider.setAddress(providerPharmacy.getProvider().getAddress());
		provider.setEmail(providerPharmacy.getProvider().getEmail());
		provider.setPhone(providerPharmacy.getProvider().getPhone());
		provider.setPhone2(providerPharmacy.getProvider().getPhone2());
		provider.setFax(providerPharmacy.getProvider().getFax());
		provider.setSocialReason(providerPharmacy.getProvider().getSocialReason());
		provider.setDateCreation(providerPharmacy.getProvider().getDateCreation());
		Locality loc = new Locality(tempLocality.getLocalityPK().getRegionId(), tempLocality.getLocalityPK().getLocalityId(),tempLocality.getName(),tempLocality.getInitials(),tempLocality.getArea(), tempLocality.getActive());
		provider.setLocality(loc);
		configServiceProducts.updateProvider(provider);
		return provider;
    }
}   

